package com.netty.bytebuf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

import java.nio.charset.Charset;

/**
 * @auther: cc.ly
 * @date: 2019/1/5/005
 */

public class Test02 {
    public static void main(String[] args) {
        //创建一个字符串的ByteBuf.容量默认是放入数据的3倍.不够会自动扩容
        ByteBuf byteBuf = Unpooled.copiedBuffer("你hello world", Charset.forName("utf-8"));
        System.out.println(byteBuf);
        //true:标示bytebuf就是一个堆上的缓存，堆上的缓存是以字节数组形式存放的
        if (byteBuf.hasArray()) {
            byte[] array = byteBuf.array();
            System.out.println(new String(array, Charset.forName("utf-8")));
            //
            System.out.println("byteBuf.arrayOffset():" + byteBuf.arrayOffset());
            System.out.println("byteBuf.readerIndex():" + byteBuf.readerIndex());
            System.out.println("byteBuf.writerIndex():" + byteBuf.writerIndex());
            System.out.println("byteBuf.capacity():" + byteBuf.capacity());
            System.out.println("byteBuf.readableBytes():" + byteBuf.readableBytes());
            byteBuf.markReaderIndex();
            //可读的字节数。等于writerIndex - readerIndex
            for (int i = 0; i < byteBuf.readableBytes(); i++) {
                System.out.println((char) byteBuf.getByte(i));
            }
            //从readindex为0的位置开始打印，打印4个字节
            System.out.println(byteBuf.getCharSequence(0, 4, Charset.forName("utf-8")));
            //从readindex为4的位置开始打印，打印6个字节
            System.out.println(byteBuf.getCharSequence(4, 6, Charset.forName("utf-8")));

        }
    }
}
